﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;

namespace Fis.Win.Forms
{
    public partial class BillListForm : BaseForm, IDataTrans
    {
        Dictionary<string, DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit> registry
            = new Dictionary<string, DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit>();

        System.Collections.Hashtable filterModel = new System.Collections.Hashtable();

        public override string Message
        {
            get
            {
                return iMessage.Caption;
            }
            set
            {
                iMessage.Caption = value;
                ShowMessage(value);
            }
        }

        public bool ShowBarManager
        {
            set { bar2.Visible = value; }
        }

        public BillListForm()
        {
            InitializeComponent();
        }

        public override void InitializeBinding()
        {
            if (!ViewModel.ContainsKey("listtype"))
                ViewModel["listtype"] = "default";
            if (ViewState == Agile.Engine.View.ViewState.Modify)
            {
                if (ViewModel["Action"].Equals("凭证审核"))
                {
                    iCertificateAudit.Caption = "批量审核";
                }
                else
                {
                    iCertificateAudit.Caption = "批量取审";
                }
                iCertificateAudit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            var data = ViewModel["viewData"] as DataTable;
            InitializeAidsValue(data);
            gridControl1.DataSource = data;

            reBillType.DataSource = CacheContext.GetCache("BILLTYPE");
            reAccount.DataSource = CacheContext.LowerAccountCache();
            UIUtils.LookUpBinding(reSync, CacheContext.YesNoCache(), "display", "value");
            UIUtils.LookUpBinding(repState, CacheContext.BillStatusCache(), "display", "value");
            UIUtils.LookUpBinding(repUser, CacheContext.GetCache("TUSER"), "FUSERNAME", "SID");

            foreach (var i in registry.AsEnumerable())
            {
                var s = CacheContext.GetCache("TAIDS").Select(string.Format("FGROUP='{0}'", i.Key));
                if (s.Length > 0)
                {
                    UIUtils.LookUpBinding(i.Value, s.CopyToDataTable(), "FNAME", "SID");
                }
            }

            gridView1.BestFitColumns();
        }

        void InitializeAidsValue(DataTable data)
        {
            foreach (var i in registry.AsEnumerable())
            {
                var field = "Aids" + i.Key;

                data.Columns.Add(field);
            }

            var value = data.Select("len(FHSVALUE)>0");

            foreach (var d in value)
            {
                AidsValueParse(d);
            }
        }

        void AidsValueParse(DataRow data)
        {
            var value = data["FHSVALUE"].ToString();
            foreach (var v in value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var key = "Aids" + v.Substring(0, 1);
                data[key] = v.Substring(2, 36);
            }
        }

        public override void InitializeViewUI()
        {
            var aids = CacheContext.GetCache("aidsgroup");
            var count = gridView1.Columns.Count;
            foreach (var i in aids.AsEnumerable())
            {
                var edit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
                edit.NullText = string.Empty;
                this.gridControl1.RepositoryItems.Add(edit);

                var col = gridView1.Columns.AddVisible("Aids" + i["key"].ToString(), i["caption"].ToString());

                col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                col.AppearanceHeader.Options.UseFont = true;
                col.AppearanceHeader.Options.UseTextOptions = true;
                col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                col.MinWidth = 80;
                col.Name = "gridColumn" + count++.ToString();
                col.OptionsColumn.AllowShowHide = false;
                col.Visible = true;
                col.VisibleIndex = count;
                col.Width = 100;
                col.ColumnEdit = edit;

                registry[i["key"].ToString()] = edit;
            }
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (bar2.Visible)
            {
                var evt = e as DevExpress.Utils.DXMouseEventArgs;
                var info = gridView1.CalcHitInfo(evt.Location);
                if (info.RowHandle < 0)
                    return;

                iEdit_ItemClick(sender, null);
            }
        }

        private void iQuery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Collections.Hashtable model = new System.Collections.Hashtable();
            using (var query = new Fis.Win.Forms.BillQueryForm())
            {
                if (query.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                model["filter0"] = query.FilterMaster;
                model["filter1"] = query.FilterDetail;
                model["listtype"] = ViewModel["listtype"];
            }

            filterModel = model;
            ViewModel = ViewProvider.InitializeViewModel(filterModel);
            InitializeBinding();
        }

        private void iEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Message = string.Empty;
            var focus = gridView1.GetFocusedDataRow();
            if (focus == null) return;

            //if (focus["FCHECKED"] != DBNull.Value)
            //{
            //    Message = "凭证已审核，不可修改";
            //    return;
            //}


            var model = new System.Collections.Hashtable();
            model["SID"] = focus["SID"];



            UIManager.ShowEdit<Forms.BillEditForm>("BillEditViewProvider", Agile.Engine.View.ViewState.Modify, model);
            //if (AppSession.IsAdminUser || focus["FENTER"].Equals(AppSession.UserSID))
            //else
            //    Message = "仅主管和制单人可修改当前凭证";
        }

        private void iDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var focus = gridView1.GetFocusedDataRow();
            if (focus == null)
                return;

            if (focus["FSYNC"].Equals(1) && !AppSession.IsAdminUser)
            {
                Message = "仅主管可执行此操作";
                MessageBox.Show(Message);
                return;
            }
            else
            {
                Message = string.Empty;
            }

            if (DevExpress.XtraEditors.XtraMessageBox.Show("确定删除吗?", "提示信息", MessageBoxButtons.YesNo)
              != System.Windows.Forms.DialogResult.Yes) return;

            var model = new System.Collections.Hashtable();
            model["SID"] = focus["SID"];
            model["FSYNC"] = focus["FSYNC"];

            ViewProvider.ExecuteUpdate(model);
            ViewModel = ViewProvider.InitializeViewModel(ViewModel);
            InitializeBinding();
        }

        private void iExportXls_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Filter = "Excel文件 (*.xls)|*.xls";

                if (DialogResult.OK == dlg.ShowDialog())
                {
                    ToXls(dlg.FileName);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出成功");
                }
            }
        }

        private void iPrintView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var provider = ViewProvider as Fis.Win.Rules.BillListViewProvider;
            DataTable data = null;

            if (filterModel.Count == 0)
            {
                filterModel["filter0"] = ViewModel["filter0"];
                filterModel["filter1"] = ViewModel["filter1"];
            }

            Fis.Win.Forms.LoadingForm.ShowLoading(
                 () => { data = provider.InitPrintPreview("bill.repx", filterModel); }, null
             );

            if (data.Rows.Count == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("没有需要打印的数据");
                return;
            }
            provider.ShowPrintPreview("bill.repx", data);
        }

        private void iSync_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (Fis.Win.Utils.AppSession.RightsValidata("BOOK", "Submit"))
            {
                System.Collections.Hashtable model = new System.Collections.Hashtable();
                CreateSyncFilter(model);
                if (!ViewProvider.ExecuteUpdateXtra(model))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(Message);
                    return;
                }

                DevExpress.XtraEditors.XtraMessageBox.Show("上传成功");
                ViewModel = ViewProvider.ExecuteQuery(ViewModel);
                InitializeBinding();
            }
        }

        void CreateSyncFilter(System.Collections.Hashtable param)
        {
            var type = ViewModel["listtype"].ToString();
            var filter = string.Empty;
            switch (type)
            {
                //初始化同步
                case "init":
                    filter = " FSYNC<1 AND FSTATUS=4";
                    break;
                default:
                    filter = " FSYNC<1 AND FSTATUS=0";
                    break;
            }

            param["SyncFilter"] = filter;
            param["SyncType"] = type;
        }

        private void iCertificateAudit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Yes;
            Close();
        }

        private void iRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ViewModel = ViewProvider.InitializeViewModel(ViewModel);
            InitializeBinding();
        }

        public string FromXls(string path)
        {
            var error = string.Empty;
            var data = DataTransUtils.ReadSheet(path, Text, ref error);

            //读取出错
            if (data == null)
            {
                return "Excel格式错误或者Excel中的Sheet名称不正确。";
            }

            ///实体数据
            DataTable source = (gridControl1.DataSource as DataTable);
            DataTable schema = source.Copy();
            schema.Clear();

            foreach (DataRow row in data.AsEnumerable())
            {
                //新行
                var newRow = schema.NewRow();

                var serial = Agile.Engine.Utils.StringUtils.IsEmpty(row["顺序号"]) ? string.Empty : row["顺序号"].ToString();
                var billkind = Agile.Engine.Utils.StringUtils.IsEmpty(row["凭证类型"]) ? string.Empty : row["凭证类型"].ToString();
                var creatime = Agile.Engine.Utils.StringUtils.IsEmpty(row["制表日期"]) ? string.Empty : row["制表日期"].ToString();
                var summary = Agile.Engine.Utils.StringUtils.IsEmpty(row["摘要"]) ? string.Empty : row["摘要"].ToString();
                var acccode = Agile.Engine.Utils.StringUtils.IsEmpty(row["会计科目"]) ? string.Empty : row["会计科目"].ToString();
                var jie = Agile.Engine.Utils.StringUtils.IsEmpty(row["借方金额"]) ? string.Empty : row["借方金额"].ToString();
                var dai = Agile.Engine.Utils.StringUtils.IsEmpty(row["贷方金额"]) ? string.Empty : row["贷方金额"].ToString();

                #region 空值验证

                if (string.IsNullOrEmpty(serial) && string.IsNullOrEmpty(acccode))
                {
                    continue;
                }

                //顺序号不能为空
                if (string.IsNullOrEmpty(serial))
                {
                    return string.Format("导入失败，原因：顺序号不能为空");
                }
                //凭证类型不能为空
                if (string.IsNullOrEmpty(billkind))
                {
                    return string.Format("导入失败，原因：顺序号{0}的凭证类型为空", serial);
                }
                //制表日期不能为空
                if (string.IsNullOrEmpty(creatime))
                {
                    return string.Format("导入失败，原因：顺序号{0}的制表日期为空", serial);
                }
                //摘要不能为空
                if (string.IsNullOrEmpty(summary))
                {
                    return string.Format("导入失败，原因：顺序号{0}的摘要为空", serial);
                }
                //会计科目不能为空
                if (string.IsNullOrEmpty(acccode))
                {
                    return string.Format("导入失败，原因：顺序号{0}的会计科目为空", serial);
                }
                #endregion

                #region 数据转换

                newRow["FSEQUENCE"] = serial;

                var billTypeRow = CacheContext.GetCache("BILLTYPE").Select(string.Format("caption='{0}'", billkind));
                if (billTypeRow.Length == 0)
                {
                    return string.Format("导入失败，原因：顺序号{0}的凭证类型[{1}]无效", serial, billkind);
                }
                newRow["FBILLTYPE"] = billTypeRow[0]["key"];
                var createdate = DateTime.MinValue;
                DateTime.TryParse(creatime, out createdate);
                if (createdate.Equals(DateTime.MinValue))
                {
                    return string.Format("导入失败，原因：顺序号{0}的制表日期[{1}]无效", serial, creatime);
                }
                newRow["FENTERDATE"] = createdate;
                newRow["FEXPLANATION"] = summary;

                var accRow = CacheContext.GetCache("TACCOUNT").Select(string.Format("FCODE='{0}'", acccode));
                if (accRow.Length == 0)
                {
                    return string.Format("导入失败，原因：顺序号{0}的会计科目[{1}]无效", serial, acccode);
                }
                newRow["FACCOUNTCODE"] = accRow[0]["SID"];

                decimal jAmount = 0m, dAmount = 0m;
                decimal.TryParse(jie, out jAmount);
                newRow["FDEBITAMOUNT"] = jAmount;
                decimal.TryParse(dai, out dAmount);
                newRow["FCREDITAMOUNT"] = dAmount;

                newRow["FENTER"] = AppSession.UserSID;
                newRow["FSTATUS"] = 4;
                newRow["FSYNC"] = 0;
                newRow["FNO"] = serial;

                #endregion

                schema.Rows.Add(newRow);
            }

            ViewModel["viewData"] = schema;
            gridControl1.DataSource = schema;

            return string.Empty;
        }

        public void ToXls(string path)
        {
            var option = new DevExpress.XtraPrinting.XlsExportOptions();
            option.SheetName = Text;

            reAccount.DisplayMember = "FCODE";
            gridControl1.ExportToXls(path, option);
            reAccount.DisplayMember = "FDETAILNAME";
        }

        private void BillListForm_Load(object sender, EventArgs e)
        {
        }
    }
}
